package es.upm.dit.gsi.webIV0;



import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class WebIV0Activity extends Activity {
	
	private static int count=0;
	private static int mode=0;
	private ListView mConversationView;
    private static CustomArrayAdapter mConversationArrayAdapter;

    private EditText mOutEditText;
    private static Button mSend;
	
    private Intent intent;
	private ServiceConnection conn;
	private Messenger mMessenger;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); //eliminar titulo

       // Conexión con el servicio
		
        intent = new Intent(getBaseContext(), Messenger.class);
        startService(intent);
        setContentView(R.layout.main);
        conn = new ServiceConnection() {
        	@Override
        	public void onServiceConnected(ComponentName className, IBinder service) {
        		mMessenger = ((Messenger.LocalBinder)service).getService();
				Toast.makeText(getBaseContext(),"Connected to service"+mMessenger.toString(),Toast.LENGTH_LONG).show();

        		
        		 
        	}
        	@Override
        	public void onServiceDisconnected(ComponentName className) {
        		mMessenger = null;
        		stopService(intent);
        		finish();
        	}
        };

        bindService(intent, conn,  BIND_AUTO_CREATE);

        //Conversation issues
        
        mConversationArrayAdapter = new CustomArrayAdapter(this, R.layout.bubble);	
        
        mConversationView = (ListView) this.findViewById(R.id.conversacion);
		// Set the ListView adapter
		mConversationView.setAdapter(mConversationArrayAdapter);
		
		 
	        //lv.setTextFilterEnabled(true);

	        mConversationView.setOnItemClickListener(new OnItemClickListener() {
	          public void onItemClick(AdapterView<?> parent, View view,
	              int position, long id) {
	            // When clicked, show a toast with the TextView text
	            if (mode==0){
	            cleanAll();
	            reply("Ok, I'll write it down!");
	            reply("what would you do there?");
	            }
	          }
	        });
		//Text
		 mOutEditText = (EditText) findViewById(R.id.edit_text_out);
	        mOutEditText.setInputType(EditorInfo.IME_ACTION_DONE);
	        mOutEditText .setOnEditorActionListener(new OnEditorActionListener() {
		        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { //not used
		            if (actionId == EditorInfo.IME_ACTION_DONE) {
		            	InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		            	in.hideSoftInputFromWindow(mOutEditText.getApplicationWindowToken(), 0); 
	            		String message = mOutEditText.getText().toString();
		            
	            			sendMessage(message);
	            			mOutEditText.setText(null); 
	            			
		            }
		            return false;
		        }	
	        });
	             
	        //Send button
	        mSend = (Button) findViewById(R.id.button_send);
	        mSend.setOnClickListener(new OnClickListener() {
	            public void onClick(View v) {
	            	
	            	InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	            	in.hideSoftInputFromWindow(mOutEditText.getApplicationWindowToken(), 0); 
	            	String message = mOutEditText.getText().toString();
	            	if (mode==0){
		            	sendPlanMessage(message);

	            	} else {
		            	sendTaskMessage(message);

	            	}
	            	//sendTaskMessage(message);
	            	//sendDecissionMessage(message);
	            		mOutEditText.setText(""); 
	            			
	            }
	            
	        });
    }
   


	private void sendMessage(String message) {
		mConversationArrayAdapter.add(new Mensajes(message, "user", null));
		
	}
	
	private void sendPlanMessage(String message){
		mConversationArrayAdapter.add(new Mensajes (message, "user",null));
		//String planMessage= message.toString();
		planReply(message);
		
		
	}
	
	private void sendTaskMessage(String message){
		mConversationArrayAdapter.add(new Mensajes (message, "user",null));
		//String planMessage= message.toString();
		taskReply(message);
		
		
	}
	
	private void sendDecissionMessage(String message){
		mConversationArrayAdapter.add(new Mensajes (message, "user",null));
		
		if(message.contains("first")){
			Toast.makeText(getBaseContext(), "You have selected the first option", Toast.LENGTH_LONG);

			reply("The first one? Ok, I'll write it down");
			Toast.makeText(getBaseContext(), "You have selected the first option", Toast.LENGTH_LONG);
		}else if(message.contains("second")){
			reply("The second one? Ok, I'll write it down");
			Toast.makeText(getBaseContext(), "You have selected the second option", Toast.LENGTH_LONG);

		}else if(message.contains("third")){
			reply("The third one? Ok, I'll write it down");
			Toast.makeText(getBaseContext(), "You have selected the third option", Toast.LENGTH_LONG);

		}else{
			reply("I don't understand");

		}
	}
	
	private void reply (String message){
		mConversationArrayAdapter.add(new Mensajes(message, null, "bot"));

	}

	private void sillyReply(){
		String[] conv=getResources().getStringArray(R.array.conversacion);
		mConversationArrayAdapter.add(new Mensajes(conv[count], null, "bot"));
		count++;
	}
	
	private void planReply(String message){
		if (mMessenger==null){
			Toast.makeText(getBaseContext(),"Problems with service",Toast.LENGTH_LONG).show();

		} else{
		
		
		ArrayList<Plan> planList=mMessenger.retrievePlans(message);
		Integer i=planList.size();
		Log.v("Messenger",i.toString());
		for (Plan p : planList){
			reply(p.toString());
		}
		}
	}
	private void taskReply(String message){
		if (mMessenger==null){
			Toast.makeText(getBaseContext(),"Problems with service",Toast.LENGTH_LONG).show();

		} else{
		
		reply("Ok. Don't forget these things:");
		ArrayList<Task> taskList=mMessenger.retrieveTasks(message);
		Integer i=taskList.size();
		Log.v("Messenger",i.toString());
		String s="";
		for (Task t : taskList){
			s+="-"+t.toString()+"\n";
			//reply(t.toString());
		}
		reply(s);
		}
	}
	
	private void cleanAll(){
		mConversationArrayAdapter.clean();
		mode=1;
	}
	
	
    /**
     * Clase de apoyo para mostrar una correcta visualizacion personaliza del ListView.
     * 
     * @author avelad
     *
     */
    public class CustomArrayAdapter extends ArrayAdapter<Mensajes> {
    	@SuppressWarnings("unused")
		private Context context;
    	private ImageView userIcon;
    	private ImageView botIcon;
    	private TextView texto;
    	private LinearLayout linear;
		private LinearLayout text;
    	private List<Mensajes> conversacion = new ArrayList<Mensajes>();

    	/**
    	 * Construye un CustomArrayAdapter a partir de un contexto y de la direccion de un Layout.
    	 * 
    	 * @param context contexto en el que se crear el CustomArrayAdapter.
    	 * @param textViewResourceId direccion del Layout que se desea introduccir.
    	 */
    	public CustomArrayAdapter(Context context, int textViewResourceId) {
    		super(context, textViewResourceId);
    		this.context = context;
    	}    	
    	
    	/**
    	 * Añade un mensaje a la lista de mensajes que se muestra por pantalla.
    	 * 
    	 * @param mensaje Mensaje que se desea añadir.
    	 */
    	public void add(Mensajes mensaje){
    		conversacion.add(mensaje);
    		this.notifyDataSetChanged();


    	}
    	public void clean(){
    		conversacion.clear();
    		this.notifyDataSetChanged();

    	}
    	
    	public int getNumberMensaje(Mensajes mensaje){    		
    		return conversacion.indexOf(mensaje);
    		
    	}
    	
    	/**
    	 * Devuelve el numero de mensajes que contiene la lista.
    	 * 
    	 * @return int longitud de la lista.
    	 */
    	public int getCount() {
    		return this.conversacion.size();
    	}

    	/**
    	 * Obtiene un elemento Mensajes de la lista.
    	 * 
    	 * @param index posicion de la que desea obtener el mensaje
    	 * @return Mensajes mensaje que a partir de index se deseaba obtener.
    	 */
    	public Mensajes getItem(int index) {
    		return this.conversacion.get(index);
    	}

    	/**
    	 * Obtiene un View de la lista, para posteriormente ser mostrado por pantalla.
    	 * 
    	 * @param position elemento del cual se desea obtener el View.
    	 * @param convertView ekemento View de la lista(genérico).
    	 * @param parent 
    	 * @return View a partir de los paramentros devuelve View para ser mostrado por pantalla del elemento que se desea obtener.
    	 */
    	public View getView(int position, View convertView, ViewGroup parent) {

    		View row = convertView;
    		
    		if(row==null){
    			LayoutInflater inflater=getLayoutInflater();
    			row=inflater.inflate(R.layout.bubble, parent, false);
    		}
    		// Get item
    		Mensajes mensajes = getItem(position);
    		
    		// Get reference to ImageView
    		//userIcon = (ImageView) row.findViewById(R.id.user_icon);
    		
    		// Get reference to TextView 
    		texto = (TextView) row.findViewById(R.id.bubbleText);
    		
    		// Get reference to ImageView
    		//botIcon = (ImageView) row.findViewById(R.id.bot_icon);
    		
    		//Get reference to LinearLayout
    		linear = (LinearLayout) row.findViewById(R.id.linear_layout);
    		text = (LinearLayout) row.findViewById(R.id.linearText);
    		
    		
    		//Set menssage name
    		texto.setText(mensajes.toString());
    		texto.setTextColor(Color.BLACK);
    		   		
    			
    		// Set icon usign the position
    		if(mensajes.user() == 1){	
    			//userIcon.setImageResource(R.drawable.user);
    			//botIcon.setImageBitmap(null);
    			linear.setBackgroundColor(Color.TRANSPARENT);
    			linear.setGravity(Gravity.LEFT);
    			text.setBackgroundResource(R.drawable.bocadillo_user2);
    		}
    		if(mensajes.bot() == 1){
    			//botIcon.setImageResource(R.drawable.icon);
    			//userIcon.setImageBitmap(null);
    			linear.setBackgroundColor(Color.TRANSPARENT);
    			linear.setGravity(Gravity.RIGHT);
    			text.setBackgroundResource(R.drawable.bocadillo_bot2);
    		}
    		return row;  
    	}

       
    
}





}